/**
 * 
 */
package edu.cmu.cs.webapp.ioms.actions.order;

import java.util.Date;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.IngredientDAOImpl;
import edu.cmu.cs.webapp.ioms.models.Ingredient;
import edu.cmu.cs.webapp.ioms.ui.dialogs.order.InventoryRechargeDialog;
import edu.cmu.cs.webapp.ioms.views.InventoryView;

/**
 * @author Christian
 * 
 */
public class PurchaseInventoryViewAction implements IViewActionDelegate {
	private InventoryView view;
	private Ingredient model;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IViewActionDelegate#init(org.eclipse.ui.IViewPart)
	 */
	@Override
	public void init(IViewPart view) {
		this.view = (InventoryView) view;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		if (model != null) {
			InventoryRechargeDialog dlg = new InventoryRechargeDialog(this.view
					.getSite().getShell(), this.model);

			if (dlg.open() == IDialogConstants.OK_ID) {
				try {
					Ingredient ing = dlg.getModel();
					ing.setLastUpdate(new Date(System.currentTimeMillis()));
					new IngredientDAOImpl().updateIng(ing);

					// new IngredientDAOImpl().chargeInventory(dlg.getModel()
					// .getIng_id(), dlg.getModel().getInventory());

				} catch (DataAccessException e) {
					// Alerts.getInstance().detailError("Data Access Error",
					// e.getLocalizedMessage(), e);
				}
				this.view.refreshInventoryView();
			}

		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action
	 * .IAction, org.eclipse.jface.viewers.ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			if (obj instanceof Ingredient) {
				this.model = (Ingredient) obj;
			}
		}
	}

}
